import flask
from flask import Flask
import os
from datetime import timedelta

app = Flask(__name__, template_folder='.')


@app.route('/')
def root():
    return flask.redirect('/login')


'''
登录页面
'''


@app.route('/login', methods=['GET'])
def login():
    if flask.request.method == 'GET':
        return flask.render_template('static/templates/login.html')


'''
连接数据库，验证登录信息，目前没有验证功能，点击就登录
TODO: 连接数据库
'''
user_dict = {
    'admin': 'admin'
}


@app.route('/check', methods=['POST'])
def check():
    id = flask.request.values['id']
    psw = flask.request.values['psw']
    try:
        if user_dict[id] == psw:
            flask.session['username'] = id
            return 'correct'
        else:
            return 'wrong'
    except Exception as e:
        print('Could not find user:', e)
        return 'not found'


'''
上传页面
TODO: 所有
'''


@app.route('/upload', methods=['GET', 'POST'])
def index():
    if flask.session.get('username') is None:
        return flask.redirect('/login')
    if flask.request.method == 'GET':
        return flask.render_template('static/templates/upload.html')
    if flask.request.method == 'POST':
        img = flask.request.files.get('upload_img')
        if img is None:
            return 'No File'
        else:
            file_path = 'static/proced_video/' + img.filename
            img.save(file_path)  # 保存文件
            # TODO: 调用算法
            return file_path


if __name__ == '__main__':
    app.secret_key = 'key123'
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
    app.run(host='0.0.0.0', port=5000)
